package umich.max.geolocation.statistics;

import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import max.nlp.dal.annotations.DBpediaAnnotation;
import max.nlp.dal.blog.blogger.BlogAuthorProfile;
import max.nlp.dal.blog.blogger.BloggerBlog;
import max.nlp.dal.blog.blogger.BloggerDB;
import max.nlp.dal.blog.blogger.BloggerPost;
import max.nlp.dal.blog.blogger.ParsedLocation;
import max.nlp.util.MapSorter;

import com.mongodb.DBCursor;

public class BlogStatistics {
	private BloggerDB db = BloggerDB.getInstance();

	public static void main(String[] args) {
		BlogStatistics b = new BlogStatistics();
//		HashMap<String, Integer> counts = b.countPostsFromState();
//		MapSorter<String,Integer> g = new MapSorter<String,Integer>();
//		List<Entry<String, Integer>> sortedCounts = g.sortMap(counts);
//		for (int i = 0; i < sortedCounts.size(); i++){
//			System.out.println(sortedCounts.get(i).getKey() + " [" + sortedCounts.get(i).getValue() + "]" );
//		}
		b.countPostsWithLocation();
	}

	public void countPostsWithDBpediaAnnotation() {
		DBCursor itr = db.getBlogIterator();
		int numPosts = 0;
		while (itr.hasNext()) {
			BloggerBlog b = new BloggerBlog(itr.next());
			for (BloggerPost p : b.getPosts()) {
				if (p.getDBpediaAnnotation().size() > 0) {
					numPosts++;
					String text = p.getCleanContent();
					System.out.println(text);
					for (DBpediaAnnotation a : p.getDBpediaAnnotation()) {
						System.out.println("["
								+ a.getUri()
								+ "] "
								+ text.substring(a.getStartOffset(),
										a.getEndOffset() + a.getStartOffset()));
					}
				}
			}
		}

		System.out.println("Number of blogs with dbpedia annotations: "
				+ numPosts);

	}
	
	@SuppressWarnings("unused")
	public void countPostsWithLocation() {
		DBCursor itr = db.getBlogIterator();
		int numPosts = 0;
		int numPostWithLocs = 0;
		int numBlogsWithLocPost = 0;
		int numBlogs = 0;
		while (itr.hasNext()) {
			BloggerBlog b = new BloggerBlog(itr.next());
			boolean blogCounted = false;
			numBlogs++;
			for (BloggerPost p : b.getPosts()) {
				numPosts++;
				if (p.getLocations().size() > 0) {
					numPostWithLocs++;
					if (!blogCounted) {
						blogCounted = true;
						numBlogsWithLocPost++;
					}
				}
			}
		}
		System.out.println(numPostWithLocs);
		System.out.println(numPosts);
	}

	public HashMap<String, Integer> countPostsFromState() {
		DBCursor itr = db.getBlogIterator();
		HashMap<String, Integer> counts = new HashMap<String, Integer>();

		while (itr.hasNext()) {
			BloggerBlog b = new BloggerBlog(itr.next());
			BlogAuthorProfile profile = db.findProfileForBlog(b);
			ParsedLocation loc = profile.getParsedLocation();
			if (loc != null && loc.getState() != null) {
				String state = loc.getState();
				Integer count = counts.get(state);
				if (count == null)
					counts.put(state, 1);
				else
					counts.put(state, count + 1);
			}
		}
		return counts;
	}

}
